<template>
  <div class="script-browser-backdrop" @click="closeBrowser">
    <div class="script-browser-modal" @click.stop>
      <div class="script-header">
        <h2>剧本浏览</h2>
        <button @click="closeBrowser" class="close-btn">×</button>
      </div>

      <div class="script-tabs">
        <button
          @click="switchTab('all')"
          :class="{ active: currentTab === 'all' }"
          class="tab-btn"
        >
          全部剧本
        </button>
        <button
          v-if="isLoggedIn"
          @click="switchTab('my')"
          :class="{ active: currentTab === 'my' }"
          class="tab-btn"
        >
          我的上传
        </button>
        <button
          v-if="isLoggedIn && isAdmin"
          @click="switchTab('admin')"
          :class="{ active: currentTab === 'admin' }"
          class="tab-btn admin-tab"
        >
          <span class="admin-icon">⚙️</span>
          管理员
        </button>
      </div>

      <div class="script-content">
        <!-- 非管理员标签页显示搜索过滤器和剧本列表 -->
        <div v-if="currentTab !== 'admin'">
          <div class="content-header">
            <div class="search-filters">
              <div class="search-inputs">
                <div class="search-box">
                  <input
                    v-model="searchQuery"
                    type="text"
                    placeholder="搜索剧本名称或作者..."
                    @input="debounceSearch"
                    @keydown.enter="filterScripts"
                  />
                  <button
                    v-if="searchQuery"
                    @click="clearSearch"
                    class="clear-search-btn"
                    title="清空搜索"
                  >
                    ×
                  </button>
                </div>
                
                <div class="role-search-box">
                  <input
                    v-model="roleSearchQuery"
                    type="text"
                    placeholder="搜索角色（如：占卜师、恶魔、镇民等）..."
                    @input="debounceRoleSearch"
                    @keydown.enter="filterScripts"
                    @focus="showRoleSearchTip = true"
                    @blur="hideRoleSearchTip"
                  />
                  <div class="search-icon">🎭</div>
                  <button
                    v-if="roleSearchQuery"
                    @click="clearRoleSearch"
                    class="clear-search-btn"
                    title="清空角色搜索"
                  >
                    ×
                  </button>
                  
                  <!-- 搜索提示 -->
                  <div 
                    v-if="showRoleSearchTip && !roleSearchQuery" 
                    class="search-tip"
                  >
                    <div class="tip-title">💡 角色搜索提示：</div>
                    <div class="tip-content">
                      <div>• 搜索具体角色：占卜师、厨师、恶魔</div>
                      <div>• 搜索角色类型：镇民、爪牙、外来者</div>
                      <div>• 支持部分匹配：输入"占"可找到"占卜师"</div>
                    </div>
                  </div>
                </div>
              </div>

              <div class="filter-options">
                <select v-model="selectedCategory" @change="filterScripts" :disabled="isLoadingCategories">
                  <option value="all">全部分类</option>
                  <option 
                    v-for="category in activeCategories" 
                    :key="category.id" 
                    :value="category.id"
                  >
                    {{ category.name }}
                  </option>
                </select>

                <select v-model="sortBy" @change="filterScripts">
                  <option value="name">按名称</option>
                  <option value="likes">按点赞</option>
                  <option value="usage">按使用</option>
                  <option value="date">按日期</option>
                </select>
              </div>
            </div>

            <div class="header-actions">
              <button @click="showCustomScript = true" class="action-btn custom-script-btn">
                自定义剧本
              </button>
              <button @click="showRanking = true" class="action-btn ranking-btn">
                排行榜
              </button>
              <button
                v-if="isLoggedIn"
                @click="showUploadModal = true"
                class="action-btn upload-btn"
              >
                上传剧本
              </button>
              <button
                @click="showLoginModal = true"
                v-if="!isLoggedIn"
                class="action-btn login-btn"
              >
                登录
              </button>
              <div v-else class="user-info">
                <span class="username" :class="{ 'admin-user': isAdmin }">
                  {{ currentUser.username }}
                  <span v-if="isAdmin" class="admin-badge">管理员</span>
                </span>
                <button @click="logout" class="action-btn logout-btn">
                  登出
                </button>
              </div>
            </div>
          </div>

          <!-- 剧本列表 -->
          <div class="scripts-container">
            <div class="scripts-grid" :key="currentTab">
              <!-- 骨架屏 - 只在首次加载时显示 -->
              <ScriptSkeleton v-if="isLoading && isLoggedIn" :count="6" />

              <!-- 标签页切换时的轻量加载指示 -->
              <div v-if="isTabLoading && isLoggedIn" class="tab-loading">
                <div class="loading-spinner"></div>
                <span>加载中...</span>
              </div>

              <!-- 剧本卡片 -->
              <div
                v-for="script in scripts"
                :key="script.id"
                class="script-card"
                @click="viewScript(script)"
              >
                <!-- 图片轮播区域 -->
                <div class="script-card-images" v-if="script.images && script.images.length > 0">
                  <ImageCarousel 
                    :images="script.images"
                    :scriptId="script.id"
                    :autoPlay="true"
                    :interval="4000"
                    :enableClick="false"
                  />
                </div>

                <div class="script-card-header">
                  <h3>{{ script.name }}</h3>
                  <div class="script-meta">
                    <span class="author">{{ script.author || "未知作者" }}</span>
                    <span class="category">{{ getCategoryDisplayName(script.category) }}</span>
                    <!-- 审核状态显示 -->
                    <span
                      v-if="currentTab === 'my'"
                      :class="['status', `status-${script.status}`]"
                    >
                      {{ getStatusText(script.status) }}
                    </span>
                    <!-- 拒绝原因显示 -->
                    <div v-if="currentTab === 'my' && script.status === 'rejected' && script.reviewNote" class="reject-reason">
                      <span class="reason-label">拒绝原因:</span>
                      <span class="reason-text">{{ script.reviewNote }}</span>
                    </div>
                  </div>
                </div>

                <div class="script-card-info" v-if="!script.images || script.images.length === 0">
                  <p class="description">
                    {{ script.description || "暂无描述" }}
                  </p>
                  <div class="stats">
                    <span class="roles"
                      >{{ script.roles?.length || 0 }} 个角色</span
                    >
                    <span class="level">{{
                      script.level || "Intermediate"
                    }}</span>
                  </div>
                </div>

                <div class="script-card-actions">
                  <button
                    @click.stop="useScript(script)"
                    class="action-btn use-btn"
                    :disabled="script.status !== 'approved'"
                  >
                    {{ script.status === "approved" ? "使用剧本" : "等待审核" }}
                  </button>
                  <button
                    v-if="isLoggedIn && script.status === 'approved'"
                    @click.stop="toggleLike(script)"
                    class="action-btn like-btn"
                    :class="{ liked: script.isLiked }"
                  >
                    ❤️ {{ script.likes || 0 }}
                  </button>
                  <!-- 我的上传标签页显示图片管理按钮 -->
                  <button
                    v-if="currentTab === 'my'"
                    @click.stop="manageImages(script)"
                    class="action-btn image-btn"
                  >
                    图片管理
                  </button>
                </div>
              </div>

              <!-- 加载更多按钮 -->
              <div v-if="hasMore && !isLoadingMore" class="load-more">
                <button @click="loadMore" class="load-more-btn">
                  加载更多
                </button>
              </div>

              <!-- 没有更多数据提示 -->
              <div v-if="!hasMore && scripts.length > 0" class="no-more">
                没有更多剧本了
              </div>

              <!-- 空状态 -->
              <div v-if="scripts.length === 0 && !isLoading && !isTabLoading" class="empty-state">
                <div class="empty-icon">📚</div>
                <h3>暂无剧本</h3>
                <p v-if="currentTab === 'all'">还没有剧本，快来上传第一个吧！</p>
                <p v-else-if="currentTab === 'my'">您还没有上传过剧本</p>
                <button
                  v-if="currentTab === 'all' && isLoggedIn"
                  @click="showUploadModal = true"
                  class="upload-btn"
                >
                  上传剧本
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 管理员标签页显示管理员面板 -->
        <div v-if="currentTab === 'admin'">
          <EmbeddedAdminPanel />
        </div>
      </div>

      <!-- 登录模态框 -->
      <LoginModal
        v-if="showLoginModal"
        @close="showLoginModal = false"
        @login-success="handleLoginSuccess"
        @register-success="handleRegisterSuccess"
      />

      <!-- 上传模态框 -->
      <ScriptUploadModal
        v-if="showUploadModal"
        @close="showUploadModal = false"
        @upload-success="handleUploadSuccess"
      />

      <!-- 排行榜模态框 -->
      <div
        v-if="showRanking"
        class="ranking-modal-backdrop"
        @click="showRanking = false"
      >
        <div class="ranking-modal" @click.stop>
          <div class="modal-header">
            <h3>剧本排行榜</h3>
            <button @click="showRanking = false" class="close-btn">
              &times;
            </button>
          </div>
          <div class="modal-content">
            <ScriptRanking 
              @close="showRanking = false" 
              @close-all="handleCloseAll"
            />
          </div>
        </div>
      </div>

      <!-- 图片管理模态框 -->
      <ImageManagementModal
        v-if="showImageManagementModal && selectedScriptForImageManagement"
        :script="selectedScriptForImageManagement"
        @close="closeImageManagementModal"
        @images-updated="handleImagesUpdated"
      />

      <!-- 剧本详情模态框 -->
      <ScriptDetailModal
        v-if="showDetailModal"
        :show="showDetailModal"
        :scriptId="selectedScript ? selectedScript.id : ''"
        :scriptType="selectedScript ? selectedScript.type : 'custom'"
        @close="closeDetailModal"
        @switch-version="switchToVersion"
        @use-script-complete="handleUseScriptComplete"
      />

      <!-- 自定义剧本模态框 -->
      <CustomScriptModal
        v-if="showCustomScript"
        @close="showCustomScript = false"
        @script-selected="handleCustomScriptSelected"
      />
    </div>
  </div>
</template>

<script>
import LoginModal from "@/components/auth/LoginModal";
import ScriptUploadModal from "@/components/scripts/ScriptUploadModal";
import ScriptRanking from "@/components/scripts/ScriptRanking";
import ScriptSkeleton from "@/components/scripts/ScriptSkeleton";
import EmbeddedAdminPanel from "@/components/scripts/EmbeddedAdminPanel";
import ScriptDetailModal from "@/components/scripts/ScriptDetailModal";
import authAPI from "@/utils/authAPI";
import scriptAPI from "@/utils/scriptAPI";
import systemAPI from "@/utils/systemAPI";
import ImageCarousel from "@/components/scripts/ImageCarousel";
import ImageManagementModal from "@/components/scripts/ImageManagementModal";
import CustomScriptModal from "@/components/scripts/CustomScriptModal";

export default {
  name: "ScriptBrowser",
  components: {
    LoginModal,
    ScriptUploadModal,
    ScriptRanking,
    ScriptSkeleton,
    EmbeddedAdminPanel,
    ScriptDetailModal,
    ImageCarousel,
    ImageManagementModal,
    CustomScriptModal,
  },
  data() {
    return {
      scripts: [],
      filteredScripts: [],
      searchQuery: "",
      roleSearchQuery: "",
      showRoleSearchTip: false,
      selectedCategory: "all",
      sortBy: "name",
      currentPage: 1,
      itemsPerPage: 20,
      showLoginModal: false,
      showUploadModal: false,
      showRanking: false,
      showCustomScript: false,
      showImageManagementModal: false,
      selectedScriptForImageManagement: null,
      showDetailModal: false,
      selectedScript: null,
      isLoading: false,
      isLoadingMore: false,
      hasMore: true,
      pagination: null,
      filters: null,
      searchTimer: null,
      roleSearchTimer: null,
      tabLoadingTimer: null,
      currentTab: "all", // 当前标签页
      isTabLoading: false, // 标签页切换时的加载状态
      cachedScripts: {
        // 缓存不同标签页的数据
        all: [],
        my: [],
      },
      // 添加响应式状态
      isLoggedIn: false,
      currentUser: null,
      categories: [],
      isLoadingCategories: false,
    };
  },
  computed: {
    totalPages() {
      // 使用服务端返回的分页信息，而不是基于本地数据计算
      return this.pagination ? this.pagination.totalPages : 1;
    },
    isAdmin() {
      return this.currentUser && this.currentUser.role === "admin";
    },
    // 检查当前标签页是否需要管理员权限
    requiresAdminPermission() {
      return this.currentTab === "admin";
    },
    // 检查当前标签页是否需要登录
    requiresLogin() {
      return this.currentTab === "my" || this.currentTab === "admin";
    },
    activeCategories() {
      return this.categories.filter(category => category.isActive);
    },
  },
  async mounted() {
    // 清除缓存
    this.clearCache();
    
    // 初始化响应式状态 - 使用异步方法
    this.isLoggedIn = await authAPI.isLoggedIn();
    this.currentUser = await authAPI.getCurrentUser();

    await this.loadCategories();
    await this.loadScripts();

    // 使用authAPI的监听机制
    this.authListener = (user, token) => {
      this.handleAuthStateChange(user, token);
    };

    authAPI.addListener(this.authListener);
    
    // 确保用户状态正确初始化
    if (this.isLoggedIn && this.currentUser) {
      console.log('初始化用户状态:', this.currentUser);
    }
  },

  beforeDestroy() {
    // 清理定时器
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
    }
    
    if (this.tabLoadingTimer) {
      clearTimeout(this.tabLoadingTimer);
    }

    // 重置所有加载状态
    this.isLoading = false;
    this.isTabLoading = false;
    this.isLoadingMore = false;
    this.isLoadingCategories = false;

    // 移除authAPI监听器
    if (this.authListener) {
      authAPI.removeListener(this.authListener);
    }
  },
  methods: {
    // 处理排行榜成功使用剧本后关闭所有界面的事件
    handleCloseAll() {
      console.log('🔄 排行榜使用剧本成功，关闭所有界面');
      // 关闭排行榜
      this.showRanking = false;
      // 关闭整个剧本浏览器
      this.$emit('close');
    },

    async loadScripts(reset = true) {
      try {
        if (reset) {
          // 只在首次加载时显示骨架屏
          if (this.scripts.length === 0) {
            this.isLoading = true;
          } else {
            // 延迟显示标签页加载状态，避免快速闪过
            this.tabLoadingTimer = setTimeout(() => {
              if (this.isTabLoading === false && this.isLoggedIn) {
                this.isTabLoading = true;
              }
            }, 200); // 200ms后如果还在加载才显示加载状态
          }
          this.currentPage = 1;
          // 不清空scripts，保持现有内容直到新数据加载完成
          // 避免闪烁问题
        } else {
          this.isLoadingMore = true;
        }

        // 确保获取最新的用户信息，并同步到组件状态
        const currentUser = await authAPI.getCurrentUser();
        this.currentUser = currentUser;
        this.isLoggedIn = await authAPI.isLoggedIn();
        
        const params = {
          page: this.currentPage,
          limit: this.itemsPerPage,
          category: this.selectedCategory,
          search: this.searchQuery,
          roleSearch: this.roleSearchQuery,
          sortBy: this.sortBy,
          status: this.currentTab === "all" ? "approved" : "all", // 全部剧本只显示已审核的
          userId: this.currentTab === "my" ? currentUser?.id : "", // 我的上传显示用户自己的
        };
        
        // 分类筛选调试信息
        if (this.selectedCategory !== "all") {
          console.log("🎯 执行分类筛选:", {
            selectedCategory: this.selectedCategory,
            categoryName: this.activeCategories.find(c => c.id === this.selectedCategory)?.name,
            params: params
          });
        }
        
        // 角色搜索调试信息
        if (this.roleSearchQuery) {
          console.log("🎭 执行角色搜索:", {
            roleSearchQuery: this.roleSearchQuery,
            searchQuery: this.searchQuery,
            params: params
          });
        }
        
        // 调试信息
        if (this.currentTab === "my") {
          console.log("🔍 加载我的上传数据:", {
            currentTab: this.currentTab,
            currentUser: currentUser,
            userId: currentUser?.id,
            isLoggedIn: this.isLoggedIn,
            params: params
          });
        }

        const result = await scriptAPI.getAllScripts(params);

        // 添加调试信息，特别关注"我的上传"标签页
        if (this.currentTab === "my") {
          console.log("📋 我的上传数据查询结果:", {
            success: result?.success,
            dataExists: !!(result?.data),
            scriptsCount: result?.data?.scripts?.length || 0,
            scripts: result?.data?.scripts || [],
            pagination: result?.data?.pagination,
            error: result?.error
          });
        }

        if (result && result.data && result.data.scripts) {
          let scripts = result.data.scripts;
          
          // 调试每个剧本的分类信息
          console.log("📋 剧本分类信息:", scripts.map(script => ({
            id: script.id,
            name: script.name,
            category: script.category,
            type: script.type
          })));
          
          // 分类筛选结果调试信息
          if (this.selectedCategory !== "all") {
            console.log("✅ 分类筛选结果:", {
              selectedCategory: this.selectedCategory,
              returnedScripts: scripts.length,
              scriptCategories: scripts.map(s => ({ 
                name: s.name, 
                category: s.category 
              })).slice(0, 5)
            });
          }
          
          // 图片信息已经包含在剧本数据中，无需额外加载
          // 批量获取点赞状态（优化：限制并发数量）
          const batchSize = 5; // 每批处理5个剧本
          const scriptsWithLikes = [];
          
          for (let i = 0; i < scripts.length; i += batchSize) {
            const batch = scripts.slice(i, i + batchSize);
            const batchResults = await Promise.all(
              batch.map(async (script) => {
                try {
                  const likesResult = await scriptAPI.getScriptLikes(script.id);
                  return {
                    ...script,
                    likes: likesResult.success ? likesResult.data.count : 0,
                    isLiked: likesResult.success ? likesResult.data.isLiked : false
                  };
                } catch (error) {
                  console.error(`获取剧本 ${script.id} 点赞状态失败:`, error);
                  return {
                    ...script,
                    likes: 0,
                    isLiked: false
                  };
                }
              })
            );
            scriptsWithLikes.push(...batchResults);
          }

          if (reset) {
            this.scripts = scriptsWithLikes;
            // 缓存当前标签页的数据
            this.cachedScripts[this.currentTab] = [...scriptsWithLikes];
          } else {
            this.scripts = [...this.scripts, ...scriptsWithLikes];
            // 更新缓存
            this.cachedScripts[this.currentTab] = [...scriptsWithLikes];
          }

          this.pagination = result.data.pagination;
          this.filters = result.data.filters;
          this.hasMore = result.data.pagination ? result.data.pagination.hasNext : false;

          // 我的上传标签页的额外调试信息
          if (this.currentTab === "my") {
            console.log("✅ 我的上传数据加载完成:", {
              scriptsLoaded: this.scripts.length,
              hasMore: this.hasMore,
              pagination: this.pagination
            });
          }
        } else if (result && result.scripts) {
          // 兼容旧的数据结构
          let scripts = result.scripts;
          
          // 图片信息已经包含在剧本数据中，无需额外加载
          if (reset) {
            this.scripts = scripts;
            this.cachedScripts[this.currentTab] = [...scripts];
          } else {
            this.scripts = [...this.scripts, ...result.scripts];
            this.cachedScripts[this.currentTab] = [...scripts];
          }

          this.pagination = result.pagination;
          this.filters = result.filters;
          this.hasMore = result.pagination ? result.pagination.hasNext : false;
        } else {
          console.log("⚠️ API返回了空数据或格式错误:", {
            result: result,
            currentTab: this.currentTab
          });
          if (reset) {
            this.scripts = [];
            this.cachedScripts[this.currentTab] = [];
          }
        }
      } catch (error) {
        console.error("❌ 加载剧本数据失败:", {
          error: error,
          message: error.message,
          currentTab: this.currentTab,
          params: {
            page: this.currentPage,
            limit: this.itemsPerPage,
            category: this.selectedCategory,
            search: this.searchQuery,
            sortBy: this.sortBy,
            status: this.currentTab === "all" ? "approved" : "all",
            userId: this.currentTab === "my" ? authAPI.getCurrentUser()?.id : ""
          }
        });
        
        if (reset) {
          this.scripts = [];
          this.cachedScripts[this.currentTab] = [];
        }
      } finally {
        // 清除标签页加载定时器
        if (this.tabLoadingTimer) {
          clearTimeout(this.tabLoadingTimer);
          this.tabLoadingTimer = null;
        }
        
        // 立即重置加载状态，避免登出时显示加载中
        // 只有在用户仍然登录时才保持加载状态
        if (!this.isLoggedIn) {
          this.isLoading = false;
          this.isLoadingMore = false;
          this.isTabLoading = false;
        } else {
          this.isLoading = false;
          this.isLoadingMore = false;
          this.isTabLoading = false;
        }
      }
    },

    async loadScriptImages(scripts) {
      // 并行加载所有剧本的图片数据
      const imagePromises = scripts.map(async (script) => {
        try {
          const result = await scriptAPI.getScriptImages(script.id);
          if (result.success && result.data && result.data.images) {
            script.images = result.data.images;
          } else {
            script.images = [];
          }
        } catch (error) {
          console.error(`加载剧本 ${script.id} 的图片失败:`, error);
          script.images = [];
        }
      });

      await Promise.all(imagePromises);
    },

    manageImages(script) {
      // 打开图片管理模态框
      this.selectedScriptForImageManagement = script;
      this.showImageManagementModal = true;
    },

    closeImageManagementModal() {
      this.showImageManagementModal = false;
      this.selectedScriptForImageManagement = null;
    },

    handleImagesUpdated() {
      // 图片更新后刷新当前剧本列表
      this.loadScripts();
    },

    closeDetailModal() {
      this.showDetailModal = false;
      this.selectedScript = null;
    },

    handleUseScriptComplete() {
      // 剧本使用完成后，关闭剧本浏览器，返回游戏界面
      console.log("🎮 剧本使用完成，关闭剧本浏览器");
      this.closeDetailModal(); // 关闭详情模态框
      this.$emit("close"); // 关闭整个剧本浏览器
    },

    switchToVersion(scriptId) {
      // 切换到新版本的剧本
      this.selectedScript = { id: scriptId };
      this.refreshData();
    },

    async loadCategories() {
      try {
        this.isLoadingCategories = true;
        const result = await systemAPI.getCategories();
        if (result.success) {
          this.categories = result.data.categories || [];
        } else {
          console.error('加载分类失败:', result.error);
        }
      } catch (error) {
        console.error('加载分类失败:', error);
      } finally {
        this.isLoadingCategories = false;
      }
    },

    async filterScripts() {
      console.log("🔍 前端分类筛选触发:", {
        selectedCategory: this.selectedCategory,
        searchQuery: this.searchQuery,
        sortBy: this.sortBy,
        currentTab: this.currentTab
      });
      
      // 重置分页并重新加载
      this.currentPage = 1;
      this.scripts = [];
      await this.loadScripts(true);
    },

    debounceSearch() {
      // 清除之前的定时器
      if (this.searchTimer) {
        clearTimeout(this.searchTimer);
      }

      // 设置新的定时器，500ms后执行搜索
      this.searchTimer = setTimeout(() => {
        this.filterScripts();
      }, 500);
    },

    debounceRoleSearch() {
      // 清除之前的定时器
      if (this.roleSearchTimer) {
        clearTimeout(this.roleSearchTimer);
      }

      // 设置新的定时器，500ms后执行角色搜索
      this.roleSearchTimer = setTimeout(() => {
        this.filterScripts();
      }, 500);
    },

    clearRoleSearch() {
      this.roleSearchQuery = "";
      this.filterScripts();
    },

    clearSearch() {
      this.searchQuery = "";
      this.filterScripts();
    },

    hideRoleSearchTip() {
      // 延迟隐藏提示，避免点击提示内容时立即消失
      setTimeout(() => {
        this.showRoleSearchTip = false;
      }, 200);
    },

    async switchTab(tab) {
      if (this.currentTab === tab) {
        console.log("⚠️ 尝试切换到相同标签页，跳过:", tab);
        return;
      }

      console.log("🔄 开始切换标签页:", {
        from: this.currentTab,
        to: tab,
        currentUser: this.currentUser,
        isLoggedIn: this.isLoggedIn
      });

      // 验证访问权限
      if (!this.validateTabAccess(tab)) {
        console.log("❌ 标签页访问权限验证失败");
        return;
      }

      // 管理员标签页不需要加载剧本数据
      if (tab === "admin") {
        console.log("🔄 切换到管理员标签页，不需要加载剧本数据");
        this.currentTab = tab;
        return;
      }

      // 如果切换到"我的上传"，强制清除所有缓存确保获取最新数据
      if (tab === "my") {
        this.clearCache();
        console.log("🔄 切换到我的上传，已清除所有缓存");
      } else {
        // 强制清除缓存，重新加载数据
        this.cachedScripts[tab] = [];
        console.log("🔄 切换到其他标签页，清除缓存:", tab);
      }
      
      // 在设置新标签页之前先确保用户状态是最新的
      this.currentUser = authAPI.getCurrentUser();
      this.isLoggedIn = authAPI.isLoggedIn();
      
      this.currentTab = tab;
      this.currentPage = 1;
      this.scripts = [];
      
      console.log("🔄 开始加载新标签页数据:", {
        tab: this.currentTab,
        currentUser: this.currentUser,
        userId: this.currentUser?.id,
        isLoggedIn: this.isLoggedIn
      });
      
      await this.loadScripts(true);
      
      console.log("✅ 标签页切换完成:", {
        tab: this.currentTab,
        scriptsCount: this.scripts.length,
        scriptsPreview: this.scripts.slice(0, 2).map(s => ({ id: s.id, name: s.name }))
      });
    },
    
    clearCache() {
      this.cachedScripts = {
        all: [],
        my: [],
        admin: []
      };
      
      // 获取当前用户ID
      const currentUser = authAPI.getCurrentUser();
      const userId = currentUser ? currentUser.id : 'anonymous';
      
      // 清除本地存储缓存
      try {
        const keys = Object.keys(localStorage)
        keys.forEach(key => {
          if (key.startsWith('script_detail_') || 
              key.startsWith(`townsquare_scripts_cache_${userId}`) ||
              key.startsWith(`script_file_${userId}_`)) {
            localStorage.removeItem(key)
          }
        })
        console.log(`已清除用户 ${userId} 的所有缓存`)
      } catch (error) {
        console.error('清除缓存失败:', error)
      }
    },

    async loadMore() {
      if (this.isLoadingMore || !this.hasMore) return;

      this.currentPage++;
      await this.loadScripts(false);
    },

    changePage(page) {
      if (page >= 1 && page <= this.totalPages) {
        this.currentPage = page;
      }
    },

    viewScript(script) {
      // 查看剧本详情
      console.log('viewScript called with script:', script)
      this.selectedScript = script;
      this.showDetailModal = true;
      console.log('selectedScript set to:', this.selectedScript)
      console.log('showDetailModal set to:', this.showDetailModal)
    },

    async useScript(script) {
      try {
        // 记录使用次数
        await scriptAPI.useScript(script.id);

        // 获取剧本的完整数据并设置为当前剧本
        const scriptResult = await scriptAPI.getScript(script.id, script.type || 'custom');
        if (scriptResult.success && scriptResult.data) {
          const scriptData = scriptResult.data;
          
          // 如果剧本包含角色数据，设置自定义角色
          if (scriptData.content && Array.isArray(scriptData.content)) {
            // 过滤掉_meta数据，只保留角色
            const roles = scriptData.content.filter(item => item.id !== '_meta');
            this.$store.commit("setCustomRoles", roles);
          }
          
          // 设置剧本版本信息
          this.$store.commit("setEdition", {
            id: script.id,
            name: script.name,
            author: script.author || "未知作者",
            description: script.description || "",
            isOfficial: false
          });
          
          // 关闭剧本浏览器
          this.$emit("close");
          
          // 使用控制台日志替代alert弹框
          console.log(`✅ 剧本"${script.name}"已加载成功！`);
        } else {
          throw new Error('获取剧本数据失败');
        }
      } catch (error) {
        console.error("❌ 使用剧本失败:", error.message);
      }
    },

    async toggleLike(script) {
      console.log('点赞按钮被点击:', script);
      
      const canLike = await this.canPerformAction("like");
      if (!canLike) {
        console.log('用户未登录，显示登录模态框');
        this.showLoginModal = true;
        return;
      }

      try {
        console.log('开始调用点赞API:', script.id);
        const result = await scriptAPI.toggleLike(script.id);
        console.log('点赞API返回结果:', result);
        
        if (result.success) {
          script.isLiked = result.data.isLiked;
          script.likes = result.data.count;
          console.log('点赞状态已更新:', { isLiked: script.isLiked, likes: script.likes });
        } else {
          console.error('点赞API返回失败:', result.error);
        }
      } catch (error) {
        console.error("点赞失败:", error);
      }
    },

    async handleLoginSuccess(user) {
      // 先更新响应式数据
      this.isLoggedIn = true;
      this.currentUser = user;

      // 等待DOM更新完成
      await this.$nextTick();

      // 关闭模态框
      this.showLoginModal = false;

      // 等待模态框关闭动画完成后再刷新数据
      setTimeout(() => {
        this.refreshData();
      }, 150); // 给模态框关闭动画留出时间
    },

    async handleRegisterSuccess(user) {
      // 先更新响应式数据
      this.isLoggedIn = true;
      this.currentUser = user;

      // 等待DOM更新完成
      await this.$nextTick();

      // 关闭模态框
      this.showLoginModal = false;

      // 等待模态框关闭动画完成后再刷新数据
      setTimeout(() => {
        this.refreshData();
      }, 150); // 给模态框关闭动画留出时间
    },

    async handleUploadSuccess() {
      this.showUploadModal = false;

      // 先更新用户状态，确保获取最新信息
      this.currentUser = authAPI.getCurrentUser();
      this.isLoggedIn = authAPI.isLoggedIn();

      // 等待DOM更新完成
      await this.$nextTick();

      console.log("🚀 上传成功，准备刷新数据:", {
        currentTab: this.currentTab,
        isLoggedIn: this.isLoggedIn,
        userId: this.currentUser?.id
      });

      // 等待一段时间再刷新数据，确保服务器端处理完成
      this.refreshDataWithRetry(0, 3); // 最多重试3次
    },

    // 带重试机制的数据刷新
    async refreshDataWithRetry(attempt, maxAttempts) {
      const delay = 800 + (attempt * 400); // 递增延迟：800ms, 1200ms, 1600ms
      
      console.log(`🔄 第${attempt + 1}次尝试刷新数据，延迟${delay}ms`);
      
      setTimeout(async () => {
        try {
          // 清除缓存，确保获取最新数据
          this.cachedScripts = {
            all: [],
            my: [],
            admin: []
          };
          
          // 记录刷新前的剧本数量
          const beforeCount = this.scripts.length;
          
          // 上传成功后自动切换到"我的上传"标签
          if (this.isLoggedIn) {
            if (attempt === 0 && this.currentTab !== "my") {
              // 第一次尝试且不在"我的上传"标签页：切换标签页
              console.log(`🔄 切换到我的上传标签页 (尝试 ${attempt + 1}/${maxAttempts})`);
              await this.switchTab("my");
            } else {
              // 已经在"我的上传"标签页或重试：直接重新加载数据
              console.log(`🔄 重新加载我的上传数据 (尝试 ${attempt + 1}/${maxAttempts})，当前标签页: ${this.currentTab}`);
              
              // 确保标签页设置正确
              this.currentTab = "my";
              this.scripts = [];
              this.currentPage = 1;
              
              // 强制清除缓存
              this.cachedScripts = {
                all: [],
                my: [],
                admin: []
              };
              
              await this.loadScripts(true);
            }
            
            // 检查是否成功获取到数据
            const afterCount = this.scripts.length;
            console.log(`📊 数据刷新结果 (尝试 ${attempt + 1}):`, {
              beforeCount,
              afterCount,
              hasNewData: afterCount > beforeCount || (afterCount > 0 && beforeCount === 0)
            });
            
            // 如果还没有数据且还有重试次数，则重试
            if (afterCount === 0 && attempt < maxAttempts - 1) {
              console.log(`⏰ 第${attempt + 1}次尝试未获取到数据，准备重试...`);
              this.refreshDataWithRetry(attempt + 1, maxAttempts);
            } else if (afterCount === 0) {
              console.log("❌ 所有重试都失败了，可能存在数据同步问题");
            } else {
              console.log("✅ 数据刷新成功！");
            }
          } else {
            // 清除当前数据并重新加载
            this.scripts = [];
            await this.loadScripts(true);
          }
        } catch (error) {
          console.error(`❌ 第${attempt + 1}次刷新数据失败:`, error);
          
          // 如果还有重试次数，则重试
          if (attempt < maxAttempts - 1) {
            console.log(`🔄 准备进行第${attempt + 2}次重试...`);
            this.refreshDataWithRetry(attempt + 1, maxAttempts);
          } else {
            console.error("❌ 所有重试都失败了");
            // 发生错误时，至少保持界面不空白
            if (this.scripts.length === 0) {
              await this.loadScripts(true);
            }
          }
        }
      }, delay);
    },

    async logout() {
      // 立即重置所有加载状态，避免显示加载中
      this.isTabLoading = false;
      this.isLoading = false;
      this.isLoadingMore = false;
      this.isLoadingCategories = false;
      
      // 清除所有定时器
      if (this.tabLoadingTimer) {
        clearTimeout(this.tabLoadingTimer);
        this.tabLoadingTimer = null;
      }
      if (this.searchTimer) {
        clearTimeout(this.searchTimer);
        this.searchTimer = null;
      }
      
      // 清空剧本数据，避免显示旧数据
      this.scripts = [];
      this.cachedScripts = {
        all: [],
        my: [],
        admin: []
      };
      
      // 强制更新组件以确保状态变化立即生效
      this.$forceUpdate();
      
      await authAPI.logout();

      // 更新响应式数据
      this.isLoggedIn = false;
      this.currentUser = null;

      // 清除缓存
      this.clearCache();

      // 再次强制更新组件
      this.$forceUpdate();

      // 退出后刷新数据
      this.$nextTick(() => {
        this.refreshData();
      });
    },

    closeBrowser() {
      this.$emit("close");
    },



    getStatusText(status) {
      const statusNames = {
        pending: "待审核",
        approved: "已通过",
        rejected: "已拒绝",
      };
      return statusNames[status] || "未知状态";
    },

    getCategoryDisplayName(category) {
      const categoryObj = this.categories.find(c => c.id === category);
      return categoryObj ? categoryObj.name : (category || "未分类");
    },

    handleAuthStateChange(user, token) {
      console.log("🔄 认证状态变化:", {
        userId: user?.id,
        isLoggedIn: !!token,
        role: user?.role,
      });

      // 保存旧的登录状态用于比较
      const wasLoggedIn = this.isLoggedIn;
      const wasAdmin = this.isAdmin;
      const oldUserId = this.currentUser?.id;

      // 更新响应式数据
      this.isLoggedIn = !!token;
      this.currentUser = user;

      // 强制更新组件以确保响应式数据变化
      this.$forceUpdate();

      // 检查登录状态是否发生变化
      const isNowLoggedIn = !!token;
      const isNowAdmin = this.isAdmin;
      const newUserId = user?.id;

      console.log("🔄 用户状态比较:", {
        wasLoggedIn,
        isNowLoggedIn,
        wasAdmin,
        isNowAdmin,
        oldUserId,
        newUserId,
        userIdChanged: oldUserId !== newUserId
      });

      if (wasLoggedIn !== isNowLoggedIn || wasAdmin !== isNowAdmin || oldUserId !== newUserId) {
        // 如果用户ID发生变化，清除缓存
        if (oldUserId !== newUserId) {
          this.clearCache();
          console.log("🔄 用户ID发生变化，已清除缓存");
        }
        
        // 重置加载状态
        this.isTabLoading = false;
        this.isLoading = false;
        this.isLoadingMore = false;
        this.isLoadingCategories = false;
        
        // 清除所有定时器
        if (this.tabLoadingTimer) {
          clearTimeout(this.tabLoadingTimer);
          this.tabLoadingTimer = null;
        }
        if (this.searchTimer) {
          clearTimeout(this.searchTimer);
          this.searchTimer = null;
        }
        
        // 强制更新组件
        this.$forceUpdate();
        
        // 如果用户登出且当前在需要登录的标签页，切换到全部剧本
        if (!isNowLoggedIn && this.requiresLogin) {
          this.currentTab = "all";
        }

        // 如果用户权限变化且当前在管理员标签页但无权限，切换到全部剧本
        if (this.currentTab === "admin" && !isNowAdmin) {
          this.currentTab = "all";
        }

        this.refreshData();
      }
    },

    // 验证用户是否有权限访问当前标签页
    validateTabAccess(tab) {
      console.log("🔐 验证标签页访问权限:", {
        tab: tab,
        isLoggedIn: this.isLoggedIn,
        currentUser: this.currentUser,
        isAdmin: this.isAdmin
      });

      // 检查登录权限
      if ((tab === "my" || tab === "admin") && !this.isLoggedIn) {
        console.log("❌ 权限验证失败：需要登录");
        this.showErrorMessage("请先登录后再访问此功能");
        this.showLoginModal = true;
        return false;
      }

      // 检查管理员权限
      if (tab === "admin" && !this.isAdmin) {
        console.log("❌ 权限验证失败：需要管理员权限");
        this.showErrorMessage("需要管理员权限才能访问此功能");
        return false;
      }

      console.log("✅ 权限验证通过");
      return true;
    },

    // 检查当前用户是否有权限执行操作
    async canPerformAction(action) {
      const isLoggedIn = await authAPI.isLoggedIn();
      const isAdmin = await authAPI.isAdmin();
      
      switch (action) {
        case "upload":
          return isLoggedIn;
        case "like":
          return isLoggedIn;
        case "admin":
          return isAdmin;
        default:
          return true;
      }
    },

    // 显示用户友好的错误消息
    showErrorMessage(message, type = "error") {
      const alertClass = type === "error" ? "error-alert" : "success-alert";
      const alert = document.createElement("div");
      alert.className = `user-alert ${alertClass}`;
      alert.textContent = message;

      document.body.appendChild(alert);

      // 3秒后自动移除
      setTimeout(() => {
        if (alert.parentNode) {
          alert.parentNode.removeChild(alert);
        }
      }, 3000);
    },

    // 显示成功消息
    showSuccessMessage(message) {
      this.showErrorMessage(message, "success");
    },

    async refreshData() {
      // 防止快速点击导致的闪烁
      if (this.isTabLoading || this.isLoading) {
        return;
      }

      // 清除所有定时器
      if (this.tabLoadingTimer) {
        clearTimeout(this.tabLoadingTimer);
        this.tabLoadingTimer = null;
      }
      if (this.searchTimer) {
        clearTimeout(this.searchTimer);
        this.searchTimer = null;
      }
      
      // 重置所有加载状态
      this.isTabLoading = false;
      this.isLoading = false;
      this.isLoadingMore = false;
      this.isLoadingCategories = false;

      // 如果当前在需要登录的标签页且用户未登录，切换到"全部剧本"
      if (this.requiresLogin && !this.isLoggedIn) {
        this.currentTab = "all";
      }

      // 如果当前在管理员标签页且用户无管理员权限，切换到"全部剧本"
      if (this.requiresAdminPermission && !this.isAdmin) {
        this.currentTab = "all";
      }

      // 管理员标签页不需要加载剧本数据
      if (this.currentTab === "admin") {
        return;
      }

      // 重新加载分类和当前标签页数据
      this.currentPage = 1;

      try {
        await this.loadCategories();
        await this.loadScripts(true);
      } catch (error) {
        console.error("❌ 刷新剧本数据失败:", error);
        // 确保错误时也重置加载状态
        this.isTabLoading = false;
        this.isLoading = false;
        this.isLoadingMore = false;
      }
    },

    // 处理自定义剧本选择
    handleCustomScriptSelected(scriptData) {
      console.log('选择自定义剧本:', scriptData);
      
      // 调用store的setCustomRoles方法来设置自定义剧本
      this.$store.commit("setCustomRoles", scriptData.roles);
      
      // 设置剧本元数据
      if (scriptData.meta) {
        this.$store.commit("setEdition", {
          id: "custom",
          name: scriptData.meta.name || "自定义剧本",
          author: scriptData.meta.author || "未知作者",
          description: scriptData.meta.description || "",
          isOfficial: false
        });
      } else {
        this.$store.commit("setEdition", {
          id: "custom",
          name: "自定义剧本",
          author: "未知作者",
          description: "",
          isOfficial: false
        });
      }
      
      // 关闭剧本浏览器
      this.$emit("close");
      
      // 使用控制台日志替代alert弹框
      console.log("✅ 自定义剧本已加载成功！");
    },
  },
};
</script>

<style scoped lang="scss">
.script-browser-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.script-browser-modal {
  position: relative;
  width: 90vw;
  max-width: 1200px;
  height: 85vh;
  background: linear-gradient(
    135deg,
    rgba(20, 20, 20, 0.95),
    rgba(40, 40, 40, 0.95)
  );
  border-radius: 12px;
  border: 2px solid rgba(255, 215, 0, 0.3);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  font-family: "Papyrus", serif;

  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(
      45deg,
      transparent 30%,
      rgba(255, 215, 0, 0.05) 50%,
      transparent 70%
    );
    pointer-events: none;
  }

  .script-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 25px;
    background: linear-gradient(
      90deg,
      rgba(255, 215, 0, 0.1),
      rgba(255, 215, 0, 0.05)
    );
    border-bottom: 1px solid rgba(255, 215, 0, 0.2);

    h2 {
      color: #ffd700;
      margin: 0;
      font-size: 24px;
      text-shadow: 0 0 10px rgba(255, 215, 0, 0.3);
    }

    .close-btn {
      background: none;
      border: none;
      color: #ffd700;
      font-size: 24px;
      cursor: pointer;
      padding: 5px;
      border-radius: 4px;
      transition: all 0.3s ease;

      &:hover {
        background: rgba(255, 215, 0, 0.1);
        transform: scale(1.1);
      }
    }
  }

  .script-tabs {
    display: flex;
    background: rgba(255, 255, 255, 0.02);
    border-bottom: 1px solid rgba(255, 215, 0, 0.1);

    .tab-btn {
      flex: 1;
      background: none;
      border: none;
      color: rgba(255, 255, 255, 0.7);
      padding: 15px 20px;
      font-family: "Papyrus", serif;
      font-size: 16px;
      cursor: pointer;
      transition: all 0.3s ease;
      position: relative;

      &:hover {
        color: #ffd700;
        background: rgba(255, 215, 0, 0.05);
      }

      &.active {
        color: #ffd700;
        background: rgba(255, 215, 0, 0.1);

        &::after {
          content: "";
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          height: 3px;
          background: linear-gradient(90deg, #ffd700, rgba(255, 215, 0, 0.6));
        }
      }
    }
  }

  .script-content {
    flex: 1;
    padding: 25px;
    overflow-y: auto;
    background: rgba(255, 255, 255, 0.02);

    &::-webkit-scrollbar {
      width: 8px;
    }

    &::-webkit-scrollbar-track {
      background: rgba(255, 255, 255, 0.1);
      border-radius: 4px;
    }

    &::-webkit-scrollbar-thumb {
      background: rgba(255, 215, 0, 0.3);
      border-radius: 4px;

      &:hover {
        background: rgba(255, 215, 0, 0.5);
      }
    }

    .content-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 25px;
      padding: 20px 0;
      border-bottom: 1px solid rgba(255, 215, 0, 0.2);

              .search-filters {
        display: flex;
        gap: 15px;
        align-items: center;
        flex-wrap: wrap;

        .search-inputs {
          display: flex;
          gap: 15px;
          align-items: center;
          flex-wrap: wrap;
        }

        .search-box {
          position: relative;
          display: flex;
          align-items: center;

          input {
            padding: 10px 35px 10px 15px;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 215, 0, 0.3);
            border-radius: 6px;
            color: #fff;
            font-size: 14px;
            width: 250px;
            transition: all 0.3s ease;

            &::placeholder {
              color: rgba(255, 255, 255, 0.5);
            }

            &:focus {
              outline: none;
              border-color: #ffd700;
              box-shadow: 0 0 10px rgba(255, 215, 0, 0.3);
            }
          }

          .clear-search-btn {
            position: absolute;
            right: 8px;
            background: none;
            border: none;
            color: rgba(255, 215, 0, 0.7);
            font-size: 18px;
            cursor: pointer;
            padding: 2px 4px;
            border-radius: 3px;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            line-height: 1;
            width: 20px;
            height: 20px;

            &:hover {
              background: rgba(255, 215, 0, 0.2);
              color: #ffd700;
            }

            &:active {
              transform: scale(0.95);
            }
          }
        }

        .role-search-box {
          position: relative;
          display: flex;
          align-items: center;

          input {
            padding: 10px 40px 10px 15px;
            background: rgba(156, 39, 176, 0.1);
            border: 1px solid rgba(156, 39, 176, 0.4);
            border-radius: 6px;
            color: #fff;
            font-size: 14px;
            width: 250px;
            transition: all 0.3s ease;

            &::placeholder {
              color: rgba(255, 255, 255, 0.5);
            }

            &:focus {
              outline: none;
              border-color: #9c27b0;
              box-shadow: 0 0 10px rgba(156, 39, 176, 0.3);
              background: rgba(156, 39, 176, 0.15);
            }
          }

          .search-icon {
            position: absolute;
            right: 12px;
            color: rgba(156, 39, 176, 0.7);
            font-size: 16px;
            pointer-events: none;
            transition: all 0.3s ease;
          }

          &:focus-within .search-icon {
            color: #9c27b0;
          }

          .clear-search-btn {
            position: absolute;
            right: 35px;
            background: none;
            border: none;
            color: rgba(156, 39, 176, 0.7);
            font-size: 18px;
            cursor: pointer;
            padding: 2px 4px;
            border-radius: 3px;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            line-height: 1;
            width: 20px;
            height: 20px;

            &:hover {
              background: rgba(156, 39, 176, 0.2);
              color: #9c27b0;
            }

            &:active {
              transform: scale(0.95);
            }
          }

          .search-tip {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: rgba(40, 40, 40, 0.95);
            border: 1px solid rgba(156, 39, 176, 0.3);
            border-radius: 6px;
            padding: 12px;
            margin-top: 4px;
            z-index: 1000;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
            animation: fadeInDown 0.2s ease-out;

            .tip-title {
              color: #9c27b0;
              font-size: 12px;
              font-weight: bold;
              margin-bottom: 6px;
            }

            .tip-content {
              font-size: 11px;
              color: rgba(255, 255, 255, 0.8);
              line-height: 1.4;

              div {
                margin-bottom: 2px;
              }
            }
          }
        }

        .filter-options {
          display: flex;
          gap: 10px;

          select {
            padding: 8px 12px;
            background: rgba(0, 0, 0, 0.6);
            border: 1px solid rgba(255, 215, 0, 0.3);
            border-radius: 4px;
            color: #fff;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s;

            &:hover {
              border-color: rgba(255, 215, 0, 0.5);
              background: rgba(0, 0, 0, 0.7);
            }

            &:focus {
              outline: none;
              border-color: #ffd700;
              background: rgba(0, 0, 0, 0.8);
              box-shadow: 0 0 0 2px rgba(255, 215, 0, 0.2);
            }

            option {
              background: rgba(0, 0, 0, 0.9);
              color: #fff;
              padding: 8px 12px;
            }
          }
        }
      }

      .header-actions {
        display: flex;
        gap: 12px;
        align-items: center;

        .action-btn {
          background: rgba(255, 215, 0, 0.15);
          border: 1px solid rgba(255, 215, 0, 0.4);
          color: #ffd700;
          padding: 10px 20px;
          border-radius: 6px;
          cursor: pointer;
          font-family: "Papyrus", serif;
          font-size: 14px;
          transition: all 0.3s ease;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);

          &:hover {
            background: rgba(255, 215, 0, 0.25);
            color: white;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
          }

          &:active {
            transform: translateY(0);
          }

          &:disabled {
            opacity: 0.5;
            cursor: not-allowed;
          }

          &.custom-script-btn {
            background: rgba(156, 39, 176, 0.15);
            border: 1px solid rgba(156, 39, 176, 0.4);
            color: #9c27b0;

            &:hover {
              background: rgba(156, 39, 176, 0.25);
              color: white;
            }
          }
        }

        .user-info {
          display: flex;
          align-items: center;
          gap: 12px;
          min-width: 0; // 允许flex项目收缩

          .username {
            color: #ffd700;
            font-size: 14px;
            font-weight: bold;
            min-width: 0; // 允许文本收缩
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            max-width: 150px; // 限制最大宽度
          }

          .logout-btn {
            flex-shrink: 0; // 防止按钮收缩
          }
        }
      }
    }
  }

  .scripts-container {
    position: relative;
    
    .scripts-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 20px;
      margin-bottom: 30px;
    }

    .script-card {
      background: rgba(255, 255, 255, 0.05);
      border: 1px solid rgba(255, 215, 0, 0.2);
      border-radius: 8px;
      padding: 20px;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 20px rgba(255, 215, 0, 0.1);
        border-color: rgba(255, 215, 0, 0.4);
      }

      .script-card-images {
        margin-bottom: 15px;
        border-radius: 8px;
        overflow: hidden;
      }

      .script-card-header {
        margin-bottom: 15px;

        h3 {
          margin: 0 0 8px 0;
          color: #ffd700;
          font-size: 18px;
          text-shadow: 0 0 8px rgba(255, 215, 0, 0.3);
        }

        .script-meta {
          display: flex;
          gap: 15px;
          font-size: 12px;
          color: rgba(255, 255, 255, 0.7);

          .author {
            color: #4a90e2;
          }

          .category {
            color: #ffd700;
          }

          .status {
            font-size: 12px;
            padding: 2px 6px;
            border-radius: 3px;

            &.status-pending {
              background: #ffa500;
              color: #000;
            }

            &.status-approved {
              background: #4caf50;
              color: #fff;
            }

            &.status-rejected {
              background: #f44336;
              color: #fff;
            }
          }
          
          .reject-reason {
            margin-top: 8px;
            padding: 8px;
            background: rgba(231, 76, 60, 0.1);
            border: 1px solid rgba(231, 76, 60, 0.3);
            border-radius: 4px;
            
            .reason-label {
              font-size: 11px;
              color: #e74c3c;
              font-weight: bold;
              margin-right: 5px;
            }
            
            .reason-text {
              font-size: 12px;
              color: rgba(255, 255, 255, 0.8);
              line-height: 1.3;
            }
          }
        }
      }

      .script-card-info {
        margin-bottom: 15px;

        .description {
          color: rgba(255, 255, 255, 0.8);
          font-size: 14px;
          line-height: 1.4;
          margin-bottom: 10px;
        }

        .stats {
          display: flex;
          gap: 15px;
          font-size: 12px;
          color: rgba(255, 255, 255, 0.6);

          .roles {
            color: #4a90e2;
          }

          .level {
            color: #ffd700;
          }
        }
      }

      .script-card-actions {
        display: flex;
        gap: 10px;
        align-items: center;

        .action-btn {
          padding: 8px 16px;
          border-radius: 4px;
          font-size: 12px;
          cursor: pointer;
          transition: all 0.3s ease;

          &.use-btn {
            background: rgba(76, 175, 80, 0.2);
            border: 1px solid rgba(76, 175, 80, 0.4);
            color: #4caf50;

            &:hover {
              background: rgba(76, 175, 80, 0.3);
            }

            &:disabled {
              opacity: 0.5;
              cursor: not-allowed;
            }
          }

          &.like-btn {
            background: rgba(255, 215, 0, 0.15);
            border: 1px solid rgba(255, 215, 0, 0.3);
            color: #ffd700;

            &:hover {
              background: rgba(255, 215, 0, 0.25);
            }

            &.liked {
              background: rgba(255, 215, 0, 0.3);
              color: white;
            }

            .like-count {
              margin-left: 5px;
              font-weight: bold;
            }
          }

          &.image-btn {
            background: rgba(255, 193, 7, 0.2);
            border: 1px solid rgba(255, 193, 7, 0.4);
            color: #ffc107;

            &:hover {
              background: rgba(255, 193, 7, 0.3);
            }
          }
        }

        .login-tip,
        .status-tip {
          font-size: 12px;
          color: rgba(255, 255, 255, 0.5);
        }
      }
    }

    .load-more {
      text-align: center;
      margin-top: 30px;

      .load-more-btn {
        background: rgba(255, 215, 0, 0.15);
        border: 1px solid rgba(255, 215, 0, 0.4);
        color: #ffd700;
        padding: 12px 24px;
        border-radius: 6px;
        cursor: pointer;
        font-family: "Papyrus", serif;
        font-size: 14px;
        transition: all 0.3s ease;

        &:hover {
          background: rgba(255, 215, 0, 0.25);
          color: white;
        }

        &:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }
      }
    }

    .no-more {
      text-align: center;
      margin-top: 30px;
      color: rgba(255, 255, 255, 0.5);
      font-size: 14px;
    }

    .empty-state {
      grid-column: 1 / -1; // 占满整个网格行
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      text-align: center;
      color: rgba(255, 255, 255, 0.6);
      font-size: 16px;
      min-width: 300px;
      min-height: 40vh;
      animation: fadeInUp 0.6s ease-out;
      
      .empty-icon {
        font-size: 4rem;
        margin-bottom: 1.5rem;
        opacity: 0.7;
      }
      
      h3 {
        margin: 0 0 1rem 0;
        font-size: 1.5rem;
        font-weight: 500;
        color: rgba(255, 255, 255, 0.8);
      }
      
      p {
        margin: 0 0 1.5rem 0;
        font-size: 1rem;
        line-height: 1.5;
        color: rgba(255, 255, 255, 0.6);
      }
      
      .upload-btn {
        background: linear-gradient(135deg, #ffd700, #ffed4e);
        color: #1a1a1a;
        border: none;
        padding: 12px 24px;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.3s ease;
        
        &:hover {
          background: linear-gradient(135deg, #ffed4e, #ffd700);
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(255, 215, 0, 0.3);
        }
        
        &:active {
          transform: translateY(0);
        }
      }
    }
  }

  .tab-loading {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: rgba(0, 0, 0, 0.3);
    backdrop-filter: blur(2px);
    color: rgba(255, 255, 255, 0.8);
    font-size: 14px;
    z-index: 10;
    opacity: 0;
    animation: fadeIn 0.3s ease-in-out forwards;

    .loading-spinner {
      width: 24px;
      height: 24px;
      border: 2px solid rgba(255, 215, 0, 0.3);
      border-top: 2px solid #ffd700;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 10px;
    }
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.fade-enter-active,
.fade-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
  transform: translateY(10px);
}

.fade-enter-to,
.fade-leave {
  opacity: 1;
  transform: translateY(0);
}

.ranking-modal-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1100;
}

.ranking-modal {
  background: linear-gradient(
    135deg,
    rgba(20, 20, 20, 0.95),
    rgba(40, 40, 40, 0.95)
  );
  border-radius: 12px;
  border: 2px solid rgba(255, 215, 0, 0.3);
  padding: 20px;
  min-width: 800px;
  max-width: 90vw;
  max-height: 90vh;
  overflow: hidden; // 移除外层滚动条
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);

  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h3 {
      margin: 0;
      color: #ffd700;
      font-size: 18px;
      text-shadow: 0 0 10px rgba(255, 215, 0, 0.3);
    }

    .close-btn {
      background: none;
      border: none;
      color: #ffd700;
      font-size: 24px;
      cursor: pointer;

      &:hover {
        color: white;
      }
    }
  }

  .modal-content {
    max-height: calc(90vh - 80px);
    overflow-y: auto; // 只保留内层滚动条
  }
}

.modal-fade-enter-active,
.modal-fade-leave-active {
  transition: opacity 0.3s ease;
}

.modal-fade-enter,
.modal-fade-leave-to {
  opacity: 0;
}

.admin-content-area {
  flex: 1;
  height: 100%;
  overflow: hidden;
}

.admin-tab {
  position: relative;

  .admin-icon {
    margin-right: 5px;
    font-size: 12px;
  }

  &::before {
    content: "";
    position: absolute;
    top: 2px;
    right: 2px;
    width: 6px;
    height: 6px;
    background: #ffd700;
    border-radius: 50%;
    box-shadow: 0 0 4px rgba(255, 215, 0, 0.6);
  }

  &.active {
    background: linear-gradient(
      135deg,
      rgba(255, 215, 0, 0.2),
      rgba(255, 215, 0, 0.1)
    );
    border: 1px solid rgba(255, 215, 0, 0.4);
  }
}

.admin-user {
  position: relative;
  display: flex;
  align-items: center;
  gap: 8px;

  .admin-badge {
    background: #ffd700;
    color: #000;
    font-size: 10px;
    padding: 2px 6px;
    border-radius: 10px;
    font-weight: bold;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
    white-space: nowrap;
  }
}

.user-alert {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 12px 20px;
  border-radius: 6px;
  font-family: "Papyrus", serif;
  font-size: 14px;
  z-index: 2000;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  animation: slideIn 0.3s ease;

  &.error-alert {
    background: rgba(220, 53, 69, 0.9);
    color: white;
    border: 1px solid rgba(220, 53, 69, 0.3);
  }

  &.success-alert {
    background: rgba(40, 167, 69, 0.9);
    color: white;
    border: 1px solid rgba(40, 167, 69, 0.3);
  }
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

@keyframes fadeInUp {
  from {
    transform: translateY(20px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

@keyframes fadeInDown {
  from {
    transform: translateY(-10px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}
</style>
